﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace PLM.ConfigurationCenter.Handler {
    public static class CmdHelper {
        //执行命令行命令,获取输出结果
        //cmd_filename: DOS程序文件名
        //arguments: 命令行参数
        public static List<(string, string)> ExecuteCommand(bool isWaitForExit, string cmd_filename, params string[] arguments) {
            var output = new List<(string, string)>();
            Process p = new Process();

            p.StartInfo.FileName = cmd_filename;//设置启动的python.exe路径
            p.StartInfo.Arguments = string.Join(" ", arguments);//设置传入参数
            p.StartInfo.CreateNoWindow = true;//不开启命令行窗口
            p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
            p.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
            p.StartInfo.UseShellExecute = false;//不开启shell
            p.StartInfo.RedirectStandardOutput = true;//将输出文本写入输出流中
            p.StartInfo.RedirectStandardError = true;//将错误写出到输出流中                    
            p.Start();
            Console.WriteLine($">> {p.StartInfo.FileName} {p.StartInfo.Arguments}");
            p.BeginErrorReadLine();
            p.BeginOutputReadLine();//开始异步读取操作
            p.OutputDataReceived += new DataReceivedEventHandler((o, e) => {
                var str = e.Data;
                output.Add(("output", str));
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(str);
                Console.ForegroundColor = ConsoleColor.White;
            });//这个一定要放在BeginOutputReadLine()后面才好用
            p.ErrorDataReceived += new DataReceivedEventHandler((o, e) => {
                var str = e.Data;
                output.Add(("error", str));
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(str);
                Console.ForegroundColor = ConsoleColor.White;
            });
            if (isWaitForExit) {
                p.WaitForExit();
            }
            p.Close();
            return output;
        }

        /// <summary>
        /// 向cmd（）传入命令行，传入"exit"则退出cmd.exe。
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public static List<(string, string)> CmdCall(bool isWaitForExit, params string[] command) => ExecuteCommand(isWaitForExit, "cmd", "/c", string.Join(" ", command));

    }
}
